(function () {
    "use strict";

    angular.module('core').controller('reportFinanceiroCR000011Controller', controller);
    controller.$inject = ['$scope', '$timeout', '$q', '$stateParams', '$alert', 'reportFinanceiroService', 'categoriaFinanceiraService'];

    function controller($scope, $timeout, $q, $stateParams, $alert, reportFinanceiroService, categoriaFinanceiraService) {
        $scope.initializeLayout('Análise de Contas a Receber');

        //[Inicializa objetos]
        $scope.state = {
            data: [],
            carregando: false,
            vazio: false,
            count: 0,
            filtro: {
                ativo: false,
                args: null,
            }
        };
        $scope.auxiliar = {
            categoriaFinanceira: {
                data: [],
                selecionada: null,
                carregando: false,
                getAll: async () => {
                    $scope.auxiliar.categoriaFinanceira.carregando = true;
                    const args = { filtro: { IndicaAnalitica: false } };
                    try {
                        const response = await categoriaFinanceiraService.getAll(args);
                        if (response.Status < 0) {
                            $alert({ text: response.Message, title: $scope.Title });
                        } else {
                            angular.copy(angular.fromJson(response.Data), $scope.auxiliar.categoriaFinanceira.data);
                            $scope.auxiliar.subcategoriaFinanceira.getAll();
                        }

                    } catch (error) {
                        $scope.tools.toastr.error('Não foi possível conectar com o(s) servidor(es)');
                        console.error(error);
                    } finally {
                        $scope.auxiliar.categoriaFinanceira.carregando = false;
                    }
                }
            },
            subcategoriaFinanceira: {
                data: [],
                carregando: false,
                getAll: async () => {
                    if (!$scope.state.filtro.args.filtro.Categoria)
                        return;

                    $scope.auxiliar.subcategoriaFinanceira.carregando = true;

                    const args = {
                        filtro: {
                            IndicaAnalitica: true,
                            Categoria: { ID: $scope.state.filtro.args.filtro.Categoria.ID }
                        }
                    };


                    try {
                        const response = await categoriaFinanceiraService.getAll(args);
                        if (response.Status < 0) {
                            $alert({ text: response.Message, title: $scope.Title });
                        } else {
                            angular.copy(angular.fromJson(response.Data), $scope.auxiliar.subcategoriaFinanceira.data);
                            $scope.auxiliar.subcategoriaFinanceira.getAll();
                        }

                    } catch (error) {
                        $scope.tools.toastr.error('Não foi possível conectar com o(s) servidor(es)');
                        console.error(error);
                    } finally {
                        $scope.auxiliar.subcategoriaFinanceira.carregando = false;
                    }
                }
            },
        };


        //[Inicializa funcões]
        $scope.initialize = async () => {

            await $scope.clearFilter();

            const _filtro = $scope.localStorage.getItem('state.filtro.args');
            if (_filtro) {
                await angular.copy(_filtro, $scope.state.filtro.args);
            }

            if ($stateParams.id)
                $scope.popups.edit.toggle($stateParams.id);

            $scope.refresh();
        };

        $scope.beforeRefresh = async () => {
            await $scope.convertFilter();
        };
        $scope.afterRefresh = async () => {
            /* trata mudanças no filtro */
            $scope.state.filtro.original.sortExpression = $scope.state.filtro.args.sortExpression;
            $scope.state.filtro.original.skip = $scope.state.filtro.args.skip;
            $scope.state.filtro.original.take = $scope.state.filtro.args.take;

            $scope.state.filtro.hasChanges = (angular.toJson($scope.state.filtro.original) !== angular.toJson($scope.state.filtro.args));

            /* armazena na localstorage para quando inicializar a página */
            $scope.localStorage.setItem('state.filtro.args', $scope.state.filtro.args);
        };
        $scope.refresh = async () => {
            try {
                await $scope.beforeRefresh();
                $scope.state.filtro.ativo = false;
                await $scope.innerRefresh();
                await $scope.afterRefresh();
            }
            catch (error) {
                $scope.clearFilter();
            } finally {
                $scope.$apply();
            }
        };
        $scope.clear = async () => {
            await $scope.clearFilter();
            $scope.refresh();
        };

        $scope.toggleFilter = async () => {
            $scope.state.filtro.ativo = !$scope.state.filtro.ativo;
        };
        $scope.convertFilter = async () => {
            /* prepara o filtro. Ex: in list de status */
        };
        $scope.clearFilter = async () => {
            $scope.state.filtro = {
                args: {
                    chaves: '',
                    filtro: null,
                    filtroDe: {
                        Vencimento: $scope.tools.date.getNMesesAtras(3)
                    },
                    filtroAte: {
                        Vencimento: $scope.tools.date.getNMeses(2)
                    },
                    sortExpression: '',
                    skip: 0,
                    take: 999999,
                },
                original: {},
                hasChanges: false
            };

            await $scope.convertFilter();
            await angular.copy($scope.state.filtro.args, $scope.state.filtro.original);
        };

        $scope.innerRefresh = async () => {
            await $scope.auxiliar.categoriaFinanceira.getAll();

            await $scope.getAll();
        };
        $scope.getAll = async () => {
            $scope.state.completo = false;
            $scope.state.filtro.args.skip = 0;
            $scope.state.carregando = true;
            try {
                const response = await reportFinanceiroService.getAllContaReceber($scope.state.filtro.args);
                if (response.Status < 0) {
                    $scope.tools.toastr.error(response.Message, 'Serviço');
                } else {
                    angular.copy(angular.fromJson(response.Data), $scope.state.data);
                    await $scope.configPivot(response.Data);
                }
                $scope.state.vazio = !($scope.state.data && $scope.state.data.length > 0);
            }
            catch (err) {
                $scope.tools.toastr.error('Não foi possível conectar com o(s) servidor(es)');
                console.error(err)
            }
            finally {
                $scope.state.carregando = false;
                $scope.$apply();
            }
        };
        $scope.configPivot = async (data) => {
            const dateFormat = $.pivotUtilities.derivers.dateFormat;
            const sortAs = $.pivotUtilities.sortAs;
            const tpl = $.pivotUtilities.aggregatorTemplates;
            const fmt = $.pivotUtilities.numberFormat({ suffix: " °C" });

            $("#pivot-table").pivotUI($scope.tools.flattenArray(data), {
                hiddenAttributes: [],
                derivedAttributes: {
                    "Vencimento.Ano": dateFormat("Vencimento", "%y", true),
                    "Vencimento.Mes": dateFormat("Vencimento", "%n", true),
                    "Vencimento.Dia": dateFormat("Vencimento", "%d", true),
                    "Vencimento.DiaSemana": dateFormat("Vencimento", "%w", true),
                    "Emissao.Ano": dateFormat("Emissao", "%y", true),
                    "Emissao.Mes": dateFormat("Emissao", "%n", true),
                    "Emissao.Dia": dateFormat("Emissao", "%d", true),
                    "Emissao.DiaSemana": dateFormat("Emissao", "%w", true),
                    "Competencia.Ano": dateFormat("Competencia", "%y", true),
                    "Competencia.Mes": dateFormat("Competencia", "%n", true),
                    "Competencia.Dia": dateFormat("Competencia", "%d", true),
                    "Competencia.DiaSemana": dateFormat("Competencia", "%w", true),
                },
                sorters: {
                    "Vencimento.Mes": sortAs(["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]),
                    "Vencimento.DiaSemana": sortAs(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]),
                    "Emissao.Mes": sortAs(["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]),
                    "Emissao.DiaSemana": sortAs(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]),
                    "Competencia.Mes": sortAs(["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]),
                    "Competencia.DiaSemana": sortAs(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]),
                },
                rows: ["Titulo", "Filial.Empresa.Nome"],
                cols: ["Vencimento.Ano", "Vencimento.Mes"],
                vals: ["ValorOriginal"],
                aggregatorName: "Soma",
                rendererName: "Heatmap",
                renderers: $.extend(
                    $.pivotUtilities.renderers,
                    $.pivotUtilities.c3_renderers,
                    $.pivotUtilities.d3_renderers
                ),
            }, true, "pt");

            $scope.tools.closeColunasDinamicas();
        };

        /*Inicializa funções*/
        $scope.initialize();

    }

})();